package cn.mymall.web.interceptor;

import cn.mymall.entity.Member;
import cn.mymall.redis.RedisHelper;
import cn.mymall.service.IMemberService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MemberHomeInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    private IMemberService memberService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie cookie = WebUtils.getCookie(request, "token");
        if (cookie == null) {
            redirect(request, response);
            return false;
        }
        String ut = cookie.getValue();
        Integer id = (Integer)redisHelper.get(ut);
        if (id==null) {
            redirect(request, response);
            return false;
        }
        Member member = memberService.getById(id);
        if (member == null) {
            redirect(request, response);
            return false;
        }
        if(!StringUtils.equalsIgnoreCase(member.getStatus(), "Y")){
            redirect(request, response);
            return false;
        }
        request.setAttribute("login_member", member);
        return true;
    }

    private void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect(request.getContextPath() + "/login?lastpage=" + request.getRequestURI());
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
